﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using viBlog.Classes;
using viBlog.Controllers;
using visinia.SmartEngine;
using visinia.SmartEngine.Modules;

public partial class Modules_viBlog_SimilarPosts_SimilarPosts : WebModule
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected override void WebModuleRender(HtmlTextWriter output)
    {
        int count = 0;
        if (Int32.TryParse((string)Settings["Count"], out count))
        {
            if (count < 1)
                return;
            int postid = 0;
            List<Post> posts = new List<Post>();
            if (Int32.TryParse(Request.QueryString["PostId"], out postid))
            {
                if ((string)Settings["PostBy"] == "Category")
                {                    
                    foreach (Category category in CategoryController.GetCategories(postid))
                    {
                        posts.AddRange(PostController.GetPosts(category, count));
                        if (posts.Count > count)
                            break;
                    }
                }
                if ((string)Settings["PostBy"] == "Tag")
                {                    
                    foreach (Tag tag in TagController.GetTags(postid))
                    {
                        posts.AddRange(PostController.GetPosts(tag, count));
                        if (posts.Count > count)
                            break;
                    }
                }
            }
            List<Post> list = new List<Post>();
            if (posts.Count > count)
                list = posts.GetRange(0, count);
            else
                list = posts;
            if (list == null)
                return;
            List<string> text = new List<string>();
            List<string> links = new List<string>();
            foreach (Post post in list)
            {
                if (post.PostId == postid)
                    continue;
                text.Add(post.Title);
                links.Add(post.Url);
            }            
            string data = WebHelpers.GenerateBulletedListHyperLinks(text.ToArray(), links.ToArray());
            if (text.Count > 0)
            {
                output.Write("<h2>Similar Posts:</h2>");
                output.Write(data);
            }
        }
    }
}
